package com.ete.app.welcome

import android.Manifest
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.ete.app.BR
import com.ete.app.R
import com.ete.app.constant.EteConstant
import com.ete.app.databinding.ActivityWelcomeBinding
import com.jkkc.lib.base.core.BaseActivity
import com.jkkc.lib.base.util.ARouterUtils
import java.io.File

/**
 * Author:LiXian
 * <p>
 * Desc:启动页
 * Version:1.0
 * date 2024/1/8 9:54
 */
@Route(path = EteConstant.ROUTER_WELCOME)
class WelcomeActivity : BaseActivity<ActivityWelcomeBinding, WelcomeModel>() {

    override fun initContentView(savedInstanceState: Bundle?): Int = R.layout.activity_welcome

    override fun initVariableId(): Int = BR.welcomeVm

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestPermission()
        binding.actWelcomeTv.setOnClickListener {
            ARouterUtils.navigation(EteConstant.ROUTER_HOME)
        }
    }

    /**
     * 请求权限
     */
    private fun requestPermission() {
        val permissions: Array<String> = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.CAMERA,
                Manifest.permission.ACCESS_NETWORK_STATE)
        val isGranted = PermissionUtils.isGranted(*permissions)
        if (isGranted) {
            allPermissionAllow()
            return
        }
        PermissionUtils.permission(*permissions)
            .callback { isAllGranted, _, deniedForever, _ ->
                if (isAllGranted) {
                    allPermissionAllow()
                } else {
                    if (deniedForever.isNotEmpty()) {
                        showPermissionDialog()
                    } else {
                        requestPermission()
                    }
                }
            }
            .request()
    }

    private fun showPermissionDialog() {
        ToastUtils.showShort("权限拒绝")
    }

    /**
     * 所有权限同意
     */
    private fun allPermissionAllow() {
        createDir()
        delayNavigation()
    }

    private fun createDir() {
        EteConstant.getDirs().forEach { path ->
            FileUtils.createOrExistsDir(path)
        }
    }

    private fun delayNavigation() {
        ThreadUtils.runOnUiThreadDelayed({
            ARouterUtils.navigation(EteConstant.ROUTER_HOME)
        }, 2000)
    }
}